# -*- coding: utf-8 -*-
import requests
import json
from utils import verify_dco_signature
from flask import Flask, request, jsonify,send_from_directory
from mongo_db import MongoDB  # 导入 MongoDB 类
from sendmail import send_email  # 导入发送邮件函数
app = Flask(__name__)

# 初始化 MongoDB 连接
mongo_uri = 'mongodb://test1:111111@localhost:27017/?tls=false&authSource=atomdco'  # 修改为您的 MongoDB 连接字符串
db_name = 'atomdco'
mongo_db = MongoDB(mongo_uri, db_name)
mongo_db.connect()  # 建立连接

@app.route('/api/v1/pushhook', methods=['POST'])
def webPushhook():
    # 获取 POST 请求中的 JSON 数据
    data = request.json
    print("push hook接收到的数据:", data)
    # 处理接收到的数据
    if data:
        #print("接收到的数据:", data)
        # 从数据中提取信息
        commit_info = data['commits'][0]
        commit_id = commit_info['id']
        branch = commit_info['url']
        commit_message = commit_info['message']
        author_name = commit_info['author']['name']
        author_email = commit_info['author']['email']
        print(f"提交信息: {commit_message}, 作者: {author_name}, 邮箱: {author_email}")
        # 验证 DCO 签名
        print("验证 DCO 签名...")
        is_signed = verify_dco_signature(commit_message, author_name, author_email)
        print(f"DCO签名验证结果: {is_signed}")
        if not is_signed:
            # DCO 验证失败，返回错误响应
            return jsonify({"status": "error", "message": "DCO signature verification failed"})
        
         # DCO 验证成功，插入记录到 MongoDB
        result_data = {
            "cid": commit_id,
            "name": author_name,
            "email": author_email,
            "branch": branch,
            "result": "pass"
        }
        
        mongo_db.insert_one('result', result_data)  # 插入到 result 集合
        # 处理数据
        response_data = {
            "status": "success",
            "message": "Webhook received",
            "data": "DCO signature verification passed"
        }

    else:
        response_data = {
            "status": "error",
            "message": "No data received"
        }

    # 返回 JSON 响应
    return jsonify(response_data)

@app.route('/api/v1/mergehook', methods=['POST'])
def webMergehook():
    # 获取 POST 请求中的 JSON 数据
    data = request.json
    print("mege hook接收到的数据:", data)
    # 处理接收到的数据
    if data:
        #print("接收到的数据:", data)
        # 获取所需的信息
        pull_request_url = data["pull_request"]["html_url"]
        branch_name = data["pull_request"]["head"]["ref"]
        committer_id = data["pull_request"]["head"]["user"]["id"]
        committer_name = data["pull_request"]["head"]["user"]["name"]
        committer_email = data["pull_request"]["head"]["user"]["email"]
        # 打印结果
        print(f"Pull Request URL: {pull_request_url}")
        print(f"分支名: {branch_name}")
        print(f"提交者ID: {committer_id}")
        print(f"提交者姓名: {committer_name}")
        print(f"提交者邮箱: {committer_email}")
        #检查是否签署了dco协议
        print("检查邮箱是否已签署DCO协议...")
        if mongo_db.find_one_by_field('user', 'email', committer_email) == None:
            #发邮件提醒
            print("邮箱未签署DCO协议,发送邮件提醒...")
            # 处理数据      
            send_email("923011111@qq.com","pwd",committer_email,"DCO协议签署提醒","请签署DCO协议,否则无法合并代码")
        else:
            print("邮箱已签署DCO协议,无需发送邮件提醒...")
            #验证本次pr的DCO签名
            print("验证本次pr的DCO签名...")
            dco_result = "DCO验证结果:"
            if mongo_db.find_one_by_field('result', 'cid', committer_id) == None:
                print(f"DCO签名验证结果:未通过")
                dco_result += "未通过"
            else:
                print(f"DCO签名验证结果:通过")
                dco_result += "通过"
            
            #调用Atomgit API接口在当前Pr页面上显示DCO签名验证结果
            # 定义变量
            owner =  data["repository"]["owner"]["login"]  # 替换为实际的owner
            repo = data["repository"]["name"]      # 替换为实际的repo
            pull_number = data["pull_request"]["number"]   # 替换为实际的PR号
            url = f"https://api.atomgit.com/repos/{owner}/{repo}/pulls/{pull_number}/comments"

            # 准备要提交的JSON数据
            data = {
                "body": dco_result,  # 替换为你想要评论的内容
                "commit_id": committer_id  # 替换为实际的commit ID
            }

            # 如果需要身份验证，添加token
            headers = {
                "Content-Type": "application/json",
                "Authorization": "Bearer 你的TOKEN"  # 替换为实际的token（如果有的话）
            }

            # 发送POST请求
            response = requests.post(url, headers=headers, data=json.dumps(data))

            # 检查响应
            if response.status_code == 201:
                print("评论提交成功:", response.json())
            else:
                print("提交失败，状态码:", response.status_code)
                print("错误信息:", response.text)
        
        # 处理数据
        response_data = {
            "code": 0,
            "message": "Webhook received",
        }
    else:
        response_data = {
            "code": 403,
            "message": "not data received"
        }

    # 返回 JSON 响应
    return jsonify(response_data)


@app.route('/dco/<path:filename>')
def serve_static_files(filename):
    return send_from_directory('static/dco', filename)

# 提供静态文件服务
@app.route('/layui/css/<path:filename>')
def serve_css(filename):
    return send_from_directory('static/layui/css', filename)

@app.route('/layui/<path:filename>')
def serve_js(filename):
    return send_from_directory('static/layui/', filename)


# 提供 signdco 接口,签署dco声明
@app.route('/api/v1/signdco', methods=['POST'])
def sginDcoHandler():
    # 获取 POST 请求中的 JSON 数据
    data = request.json
    print("signdco 接收到的数据:", data)

    #name,email,入库
    name = data['name']
    email = data['email']
    result_data = {
        "name": name,
        "email": email,
        "state": "yes"
    }
    if(mongo_db.find_one_by_field('user', 'email', email) == None):
        mongo_db.insert_one('user', result_data)  # 插入到 signdco 集合
    # 处理数据
    response_data = {
        "code": 0,
        "message": "signdco success"
    }
    # 返回 JSON 响应
    return jsonify(response_data)

# 提供 checksign 接口,查询是否签署了dco声明
@app.route('/api/v1/checksign', methods=['POST'])
def checkDcoHandler():
    # 获取 POST 请求中的 JSON 数据
    data = request.json
    print("checksign 接收到的数据:", data)

    #email查询
    email = data['email']
    result_data = mongo_db.find_one_by_field('user', 'email', email)
    if(result_data == None):
        response_data = {
            "code": 403,
            "message": "not signdco"
        }
    else:
        response_data = {
            "code": 0,
            "message": "signdco success"
        }
    # 返回 JSON 响应
    return jsonify(response_data)

# 提供签署授权接口,完成用户私有令牌的授权
@app.route('/api/v1/auth', methods=['POST'])
def authHandler():
     # 获取 POST 请求中的 JSON 数据
    data = request.json
    print("signdco 接收到的数据:", data)

    #name,email,入库
    name = data['name']
    email = data['email']
    token = data['token']
    result_data = {
        "name": name,
        "email": email,
        "token":token
    }

    if(mongo_db.find_one_by_field('user', 'email', email) == None):
        mongo_db.insert_one('user', result_data)  # 插入到 user 集合
    else:
        mongo_db.update_one_by_field('user', 'email', email, {'$set': {'token':token}})  # 更新token
    # 处理数据
    response_data = {
        "code": 0,
        "message": "auth success"
    }
    # 返回 JSON 响应
    return jsonify(response_data)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7000)
